extends MoveStateResource


class_name TurnStateResource
"""
转向
"""


## 转向的角度值,绝对角度以Vector.UP为起始量
@export_range(-180, 180, 1, "degrees") var angle: int = 0
## 是否是绝对角度(出生时的方向/当前方向)
@export var is_absolute_angle: bool = false
## 转向角速度
@export_range(0, 360, 1, "radians") var palstance: float = 0
## 转向时是否停止前进
@export var is_stop_when_turning: bool = false


func enter(ctrl: MoveController, data: Dictionary) -> void:
    var move: MoveComponent = ctrl.move_component
    data.speed = move.speed
    if is_stop_when_turning:
        move.speed = 0
    if is_absolute_angle:
        var d: Vector2 = move.wrapper.position.direction_to(ctrl.start_position)
        data.turn_direction = d.rotated(deg_to_rad(angle))
    elif angle != 0:
        data.turn_direction = move.direction.rotated(deg_to_rad(angle))
    else:
        data.turn_direction = Vector2.ZERO

# 朝指定的方向转向
func turn_to(move: MoveComponent, direction: Vector2, delta: float) -> bool:
    if direction.is_zero_approx():
        return true
    # 没有角速度,直接转向
    if palstance <= 0:
        move.direction = direction
        return true
    var to_angle: float = direction.angle_to(move.direction)
    var increment: float = palstance * delta
    if abs(to_angle) < increment:
        return true
    var turn_angle: float = move_toward(0, to_angle, increment)
    move.direction = move.direction.rotated(-turn_angle)
    return false

func update(ctrl: MoveController, data: Dictionary, delta: float, duration: float) -> bool:
    return turn_to(ctrl.move_component, data.turn_direction, delta)

func exit(ctrl: MoveController, data: Dictionary) -> void:
    if is_stop_when_turning:
        ctrl.move_component.speed = data.speed
